<template>
  <div class="settings-container">
    <div class="page-header">
      <div class="page-title">系统设置</div>
    </div>
    
    <div class="page-content">
      <el-tabs v-model="activeTab">
        <!-- 基本设置 -->
        <el-tab-pane label="基本设置" name="basic">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>基本设置</span>
              </div>
            </template>
            
            <el-form
              ref="basicFormRef"
              :model="basicForm"
              :rules="basicRules"
              label-width="120px"
            >
              <el-form-item label="系统名称" prop="system_name">
                <el-input v-model="basicForm.system_name" placeholder="请输入系统名称" />
              </el-form-item>
              <el-form-item label="系统Logo" prop="system_logo">
                <el-upload
                  class="avatar-uploader"
                  action="/api/settings/upload"
                  :show-file-list="false"
                  :on-success="handleLogoSuccess"
                  :before-upload="beforeLogoUpload"
                >
                  <img v-if="basicForm.system_logo" :src="basicForm.system_logo" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
              <el-form-item label="系统描述" prop="system_desc">
                <el-input
                  v-model="basicForm.system_desc"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入系统描述"
                />
              </el-form-item>
              <el-form-item label="管理员邮箱" prop="admin_email">
                <el-input v-model="basicForm.admin_email" placeholder="请输入管理员邮箱" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitBasicForm">保存</el-button>
                <el-button @click="resetBasicForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>
        
        <!-- 邮件设置 -->
        <el-tab-pane label="邮件设置" name="email">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>邮件设置</span>
              </div>
            </template>
            
            <el-form
              ref="emailFormRef"
              :model="emailForm"
              :rules="emailRules"
              label-width="120px"
            >
              <el-form-item label="SMTP服务器" prop="smtp_server">
                <el-input v-model="emailForm.smtp_server" placeholder="请输入SMTP服务器地址" />
              </el-form-item>
              <el-form-item label="SMTP端口" prop="smtp_port">
                <el-input v-model="emailForm.smtp_port" placeholder="请输入SMTP端口" />
              </el-form-item>
              <el-form-item label="发件人邮箱" prop="smtp_username">
                <el-input v-model="emailForm.smtp_username" placeholder="请输入发件人邮箱" />
              </el-form-item>
              <el-form-item label="邮箱密码" prop="smtp_password">
                <el-input v-model="emailForm.smtp_password" type="password" placeholder="请输入邮箱密码" show-password />
              </el-form-item>
              <el-form-item label="发件人名称" prop="smtp_sender">
                <el-input v-model="emailForm.smtp_sender" placeholder="请输入发件人名称" />
              </el-form-item>
              <el-form-item label="启用SSL" prop="smtp_ssl">
                <el-switch v-model="emailForm.smtp_ssl" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitEmailForm">保存</el-button>
                <el-button @click="resetEmailForm">重置</el-button>
                <el-button type="success" @click="testEmailConfig">测试连接</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>
        
        <!-- 短信设置 -->
        <el-tab-pane label="短信设置" name="sms">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>短信设置</span>
              </div>
            </template>
            
            <el-form
              ref="smsFormRef"
              :model="smsForm"
              :rules="smsRules"
              label-width="120px"
            >
              <el-form-item label="短信服务商" prop="sms_provider">
                <el-select v-model="smsForm.sms_provider" placeholder="请选择短信服务商" style="width: 100%">
                  <el-option label="阿里云" value="aliyun" />
                  <el-option label="腾讯云" value="tencent" />
                  <el-option label="华为云" value="huawei" />
                </el-select>
              </el-form-item>
              <el-form-item label="AccessKey" prop="sms_access_key">
                <el-input v-model="smsForm.sms_access_key" placeholder="请输入AccessKey" />
              </el-form-item>
              <el-form-item label="AccessSecret" prop="sms_access_secret">
                <el-input v-model="smsForm.sms_access_secret" type="password" placeholder="请输入AccessSecret" show-password />
              </el-form-item>
              <el-form-item label="短信签名" prop="sms_sign_name">
                <el-input v-model="smsForm.sms_sign_name" placeholder="请输入短信签名" />
              </el-form-item>
              <el-form-item label="模板ID" prop="sms_template_id">
                <el-input v-model="smsForm.sms_template_id" placeholder="请输入模板ID" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitSmsForm">保存</el-button>
                <el-button @click="resetSmsForm">重置</el-button>
                <el-button type="success" @click="testSmsConfig">测试发送</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>
        
        <!-- Webhook设置 -->
        <el-tab-pane label="Webhook设置" name="webhook">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>Webhook设置</span>
              </div>
            </template>
            
            <el-form
              ref="webhookFormRef"
              :model="webhookForm"
              :rules="webhookRules"
              label-width="120px"
            >
              <el-form-item label="Webhook URL" prop="webhook_url">
                <el-input v-model="webhookForm.webhook_url" placeholder="请输入Webhook URL" />
              </el-form-item>
              <el-form-item label="请求方式" prop="webhook_method">
                <el-radio-group v-model="webhookForm.webhook_method">
                  <el-radio label="GET">GET</el-radio>
                  <el-radio label="POST">POST</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="请求头" prop="webhook_headers">
                <el-input
                  v-model="webhookForm.webhook_headers"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入请求头，格式为JSON"
                />
              </el-form-item>
              <el-form-item label="消息模板" prop="webhook_template">
                <el-input
                  v-model="webhookForm.webhook_template"
                  type="textarea"
                  :rows="5"
                  placeholder="请输入消息模板，支持变量：${task_name}, ${status}, ${message}等"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitWebhookForm">保存</el-button>
                <el-button @click="resetWebhookForm">重置</el-button>
                <el-button type="success" @click="testWebhookConfig">测试发送</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getBasicSettings, updateBasicSettings } from '@/api/settings'
import { getEmailSettings, updateEmailSettings, testEmail } from '@/api/settings'
import { getSmsSettings, updateSmsSettings, testSms } from '@/api/settings'
import { getWebhookSettings, updateWebhookSettings, testWebhook } from '@/api/settings'

// 当前激活的标签页
const activeTab = ref('basic')

// 表单引用
const basicFormRef = ref(null)
const emailFormRef = ref(null)
const smsFormRef = ref(null)
const webhookFormRef = ref(null)

// 基本设置表单
const basicForm = reactive({
  system_name: '',
  system_logo: '',
  system_desc: '',
  admin_email: ''
})

// 邮件设置表单
const emailForm = reactive({
  smtp_server: '',
  smtp_port: '',
  smtp_username: '',
  smtp_password: '',
  smtp_sender: '',
  smtp_ssl: false
})

// 短信设置表单
const smsForm = reactive({
  sms_provider: '',
  sms_access_key: '',
  sms_access_secret: '',
  sms_sign_name: '',
  sms_template_id: ''
})

// Webhook设置表单
const webhookForm = reactive({
  webhook_url: '',
  webhook_method: 'POST',
  webhook_headers: '',
  webhook_template: ''
})

// 表单校验规则
const basicRules = {
  system_name: [
    { required: true, message: '请输入系统名称', trigger: 'blur' }
  ],
  admin_email: [
    { required: true, message: '请输入管理员邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const emailRules = {
  smtp_server: [
    { required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }
  ],
  smtp_port: [
    { required: true, message: '请输入SMTP端口', trigger: 'blur' }
  ],
  smtp_username: [
    { required: true, message: '请输入发件人邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  smtp_password: [
    { required: true, message: '请输入邮箱密码', trigger: 'blur' }
  ],
  smtp_sender: [
    { required: true, message: '请输入发件人名称', trigger: 'blur' }
  ]
}

const smsRules = {
  sms_provider: [
    { required: true, message: '请选择短信服务商', trigger: 'change' }
  ],
  sms_access_key: [
    { required: true, message: '请输入AccessKey', trigger: 'blur' }
  ],
  sms_access_secret: [
    { required: true, message: '请输入AccessSecret', trigger: 'blur' }
  ],
  sms_sign_name: [
    { required: true, message: '请输入短信签名', trigger: 'blur' }
  ],
  sms_template_id: [
    { required: true, message: '请输入模板ID', trigger: 'blur' }
  ]
}

const webhookRules = {
  webhook_url: [
    { required: true, message: '请输入Webhook URL', trigger: 'blur' },
    { type: 'url', message: '请输入正确的URL地址', trigger: 'blur' }
  ],
  webhook_method: [
    { required: true, message: '请选择请求方式', trigger: 'change' }
  ],
  webhook_template: [
    { required: true, message: '请输入消息模板', trigger: 'blur' }
  ]
}

// 获取基本设置
const getBasic = async () => {
  try {
    const res = await getBasicSettings()
    Object.keys(basicForm).forEach(key => {
      if (res.data[key] !== undefined) {
        basicForm[key] = res.data[key]
      }
    })
  } catch (error) {
    console.error('获取基本设置失败:', error)
  }
}

// 获取邮件设置
const getEmail = async () => {
  try {
    const res = await getEmailSettings()
    Object.keys(emailForm).forEach(key => {
      if (res.data[key] !== undefined) {
        emailForm[key] = res.data[key]
      }
    })
  } catch (error) {
    console.error('获取邮件设置失败:', error)
  }
}

// 获取短信设置
const getSms = async () => {
  try {
    const res = await getSmsSettings()
    Object.keys(smsForm).forEach(key => {
      if (res.data[key] !== undefined) {
        smsForm[key] = res.data[key]
      }
    })
  } catch (error) {
    console.error('获取短信设置失败:', error)
  }
}

// 获取Webhook设置
const getWebhook = async () => {
  try {
    const res = await getWebhookSettings()
    Object.keys(webhookForm).forEach(key => {
      if (res.data[key] !== undefined) {
        webhookForm[key] = res.data[key]
      }
    })
  } catch (error) {
    console.error('获取Webhook设置失败:', error)
  }
}

// 提交基本设置表单
const submitBasicForm = async () => {
  if (!basicFormRef.value) return
  
  await basicFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateBasicSettings(basicForm)
        ElMessage.success('保存成功')
      } catch (error) {
        console.error('保存基本设置失败:', error)
      }
    }
  })
}

// 提交邮件设置表单
const submitEmailForm = async () => {
  if (!emailFormRef.value) return
  
  await emailFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateEmailSettings(emailForm)
        ElMessage.success('保存成功')
      } catch (error) {
        console.error('保存邮件设置失败:', error)
      }
    }
  })
}

// 提交短信设置表单
const submitSmsForm = async () => {
  if (!smsFormRef.value) return
  
  await smsFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateSmsSettings(smsForm)
        ElMessage.success('保存成功')
      } catch (error) {
        console.error('保存短信设置失败:', error)
      }
    }
  })
}

// 提交Webhook设置表单
const submitWebhookForm = async () => {
  if (!webhookFormRef.value) return
  
  await webhookFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateWebhookSettings(webhookForm)
        ElMessage.success('保存成功')
      } catch (error) {
        console.error('保存Webhook设置失败:', error)
      }
    }
  })
}

// 重置基本设置表单
const resetBasicForm = () => {
  if (!basicFormRef.value) return
  basicFormRef.value.resetFields()
  getBasic()
}

// 重置邮件设置表单
const resetEmailForm = () => {
  if (!emailFormRef.value) return
  emailFormRef.value.resetFields()
  getEmail()
}

// 重置短信设置表单
const resetSmsForm = () => {
  if (!smsFormRef.value) return
  smsFormRef.value.resetFields()
  getSms()
}

// 重置Webhook设置表单
const resetWebhookForm = () => {
  if (!webhookFormRef.value) return
  webhookFormRef.value.resetFields()
  getWebhook()
}

// Logo上传成功回调
const handleLogoSuccess = (res) => {
  basicForm.system_logo = res.data.url
  ElMessage.success('上传成功')
}

// Logo上传前的校验
const beforeLogoUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('上传Logo只能是图片格式!')
  }
  
  if (!isLt2M) {
    ElMessage.error('上传Logo大小不能超过 2MB!')
  }
  
  return isImage && isLt2M
}

// 测试邮件配置
const testEmailConfig = async () => {
  if (!emailFormRef.value) return
  
  await emailFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await testEmail(emailForm)
        ElMessage.success('测试邮件发送成功')
      } catch (error) {
        console.error('测试邮件发送失败:', error)
      }
    }
  })
}

// 测试短信配置
const testSmsConfig = async () => {
  if (!smsFormRef.value) return
  
  await smsFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await testSms(smsForm)
        ElMessage.success('测试短信发送成功')
      } catch (error) {
        console.error('测试短信发送失败:', error)
      }
    }
  })
}

// 测试Webhook配置
const testWebhookConfig = async () => {
  if (!webhookFormRef.value) return
  
  await webhookFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await testWebhook(webhookForm)
        ElMessage.success('测试Webhook发送成功')
      } catch (error) {
        console.error('测试Webhook发送失败:', error)
      }
    }
  })
}

onMounted(() => {
  getBasic()
  getEmail()
  getSms()
  getWebhook()
})
</script>

<style lang="scss" scoped>
.settings-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .page-title {
      font-size: 20px;
      font-weight: bold;
    }
  }
  
  .page-content {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .avatar-uploader {
      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
      
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
        
        &:hover {
          border-color: var(--el-color-primary);
        }
        
        i {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }
  }
}
</style>